#include "chequeform_mnk.h"

#include <QKeyEvent>
#include <QLabel>
#include <QSqlQuery>
#include <QSqlError>
#include <QPushButton>
#include <QHeaderView>
#include <QDate>
#include <QModelIndex>
#include <QScreen>
#include <QDialog>
#include <QApplication>
#include <QDesktopWidget>
#include <QMessageBox>
#include <QThread>

#include <QScrollArea>

#include <QDebug>

#include "../components/omnibox.h"
#include "../components/smartdelegate.h"
#include "../definitions.h"
#include "../settings.h"
#include "../service.h"


ChequeForm_MnK::ChequeForm_MnK(const QString &params, QWidget *parent) :
    FormInterface(parent)
{
    this->params = params;

    loglevel = Settings::getVariables()->value("loglevel").toInt();

    firstSearch = true;

    QSettings *userSettings = Settings::getUserInstance();
    QSettings *settings = Settings::getInstance();

    QGridLayout *mainLayout = new QGridLayout(this);
    mainLayout->setSpacing(0);

    goodsTable = new QTableWidget(this);
    goodsTable->setColumnCount(8);
    goodsTable->hideColumn(0);
    goodsTable->setSelectionMode(QAbstractItemView::ContiguousSelection);
    goodsTable->setHorizontalHeaderLabels(QStringList()<<"ID"<<"Арт."<<"Товар"<<"-"<<"Кол"<<"+"<<"Цена"<<"Сумма");

    // TODO: Перенести в стили
    goodsTable->verticalHeader()->setDefaultSectionSize(settings->value("globals/table_height").toInt());
    goodsTable->setFocusPolicy(Qt::NoFocus);

    connect(goodsTable, SIGNAL(cellClicked(int,int)),this, SLOT(on_goodsTable_cellClicked(int,int)) );


    int size= userSettings->beginReadArray("cheque/preferences/goodsTable");
    for(int i=0;i<size;++i){
        userSettings->setArrayIndex(i);
        goodsTable->setColumnWidth(i, userSettings->value("width",50).toInt());
    }
    userSettings->endArray();

    SmartDelegate *dg = new SmartDelegate(this);
    dg->setReadOnly();

    SmartDelegate *dgprice = new SmartDelegate(this);
    dgprice->setPrecision(2);
    dgprice->setAlign(Qt::AlignRight | Qt::AlignVCenter);

    SmartDelegate *dgsum = new SmartDelegate(this);
    dgsum->setPrecision(2);
    dgsum->setReadOnly();
    dgsum->setAlign(Qt::AlignRight | Qt::AlignVCenter);

    SmartDelegate *dgkol = new SmartDelegate(this);
    dgkol->setPrecision(3);
    dgkol->setAlign(Qt::AlignRight | Qt::AlignVCenter);

    SmartDelegate *dgd = new SmartDelegate(this);
    dgd->setReadOnly();
    dgd->setAlign(Qt::AlignCenter);

    goodsTable->setItemDelegateForColumn(1, dg);
    goodsTable->setItemDelegateForColumn(2, dg);
    goodsTable->setItemDelegateForColumn(3, dgd);
    goodsTable->setItemDelegateForColumn(4, dgkol);
    goodsTable->setItemDelegateForColumn(5, dgd);
    goodsTable->setItemDelegateForColumn(6, dgprice);
    goodsTable->setItemDelegateForColumn(7, dgsum);

    goodsTable->setMinimumHeight(settings->value("globals/table_height").toInt() * (6));
    goodsTable->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);

    connect(goodsTable, SIGNAL(cellChanged(int,int)), this, SLOT(on_goodsTable_cellChanged(int,int)));
    connect(goodsTable, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(on_goodsTable_currentCellChanged(int,int,int,int)));

    QHBoxLayout *goodsLeftTableFooter = new QHBoxLayout();

    lastAction  = new QLabel("", this);
    goodsLeftTableFooter->addWidget(lastAction);
    goodsLeftTableFooter->addStretch(1);

    QLabel *lbSumm = new QLabel("Сумма:", this);
    lbSumm->setAlignment(Qt::AlignRight);

    summTotals = new QLabel("0.00", this);
    summTotals->setMinimumWidth(settings->value("globals/button_width").toInt() * 3);
    summTotals->setMaximumWidth(settings->value("globals/button_width").toInt() * 3);
    summTotals->setAlignment(Qt::AlignRight);


    QLabel *lbPayed = new QLabel("Оплата:", this);
    lbPayed->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    summPayed = new QLineEdit("0.00", this);
    summPayed->setMinimumWidth(settings->value("globals/button_width").toInt() * 3);
    summPayed->setMaximumWidth(settings->value("globals/button_width").toInt() * 3);
    summPayed->setAlignment(Qt::AlignRight);
    summPayed->setFocusPolicy(Qt::ClickFocus);

    connect(summPayed, SIGNAL(editingFinished()), this,  SLOT(formatSummPayed()));

    QLabel *lbReturn = new QLabel("Сдача:", this);
    lbReturn->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    summReturn = new QLabel("0.00", this);
    summReturn->setMinimumWidth(settings->value("globals/button_width").toInt() * 3);
    summReturn->setMaximumWidth(settings->value("globals/button_width").toInt() * 3);
    summReturn->setAlignment(Qt::AlignRight);

    searchModel = new QSqlQueryModel(this);
    searchModel->setQuery(settings->value("queries/cheque/goodslist").toString());

    searchProxy = new SmartSortFilterProxyModel(this);
    searchProxy->setSourceModel(searchModel);
    //qDebug()<<posInFile<<searchProxy->rowCount();

    searchTable = new QTableView(this);
    searchTable->setModel(searchProxy);
    searchTable->verticalHeader()->setVisible(false);
    searchTable->verticalHeader()->setDefaultSectionSize(settings->value("globals/button_height").toInt());

    searchTable->hideColumn(0);
    searchProxy->setHeaderData(1, Qt::Horizontal, "Штрихкод");
    searchProxy->setHeaderData(2, Qt::Horizontal, "Арт.");
    searchProxy->setHeaderData(3, Qt::Horizontal, "Название");
    searchProxy->setHeaderData(4, Qt::Horizontal, "Производитель");
    searchProxy->setHeaderData(5, Qt::Horizontal, "Цена");
    searchProxy->setHeaderData(6, Qt::Horizontal, "Остаток");

    searchTable->setItemDelegateForColumn(5, dgsum);
    searchTable->setItemDelegateForColumn(6, dgkol);

    searchTable->setSelectionMode(QAbstractItemView::SingleSelection);
    searchTable->setSelectionBehavior(QAbstractItemView::SelectRows);

    connect(searchTable, SIGNAL(clicked(QModelIndex)), this, SLOT(on_searchTable_elementSelected(QModelIndex)));

    searchTable->hide();

    goodsSelector = new QWidget(this);
    /*
    QVBoxLayout *laStretch = new QVBoxLayout();
    laStretch->addWidget(goodsSelector);
    laStretch->addStretch();
*/

    QGridLayout *laGoodsSelector = new QGridLayout();
    goodsSelector->setLayout(laGoodsSelector);

    QSqlQuery groupQuery;
    groupQuery.exec(settings->value("queries/cheque/groupslist").toString());
    int row = 0, column = 0;

    QSignalMapper *signalMapper = new QSignalMapper(this);
    while (groupQuery.next()) {
        int groupid = groupQuery.value(0).toInt();
        QString groupname = groupQuery.value(1).toString();
        if(groupname.length()>10)groupname = groupname.left(9)+"...";

        QPushButton *bt = new QPushButton(groupname, this);
        bt->setMaximumSize(settings->value("globals/button_width").toInt() * 5, settings->value("globals/button_height").toInt() );
        //bt->setMinimumSize(settings->value("globals/button_width").toInt() * 4, settings->value("globals/button_height").toInt());
        bt->setFocusPolicy(Qt::NoFocus);
        laGoodsSelector->addWidget(bt, row, column);

        connect(bt, SIGNAL(clicked()), signalMapper, SLOT(map()));
        signalMapper->setMapping(bt, "group_id="+QString::number(groupid));

        column++; if(column >= settings->value("globals/search_numcolumns").toInt()){row++; column=0;}
    }

    connect(signalMapper, SIGNAL(mapped(QString)),
            this, SLOT(on_groupSelected(QString)));

    size= userSettings->beginReadArray("cheque/preferences/searchTable");
    for(int i=0;i<size;++i){
        userSettings->setArrayIndex(i);
        searchTable->setColumnWidth(i, userSettings->value("width",50).toInt());
    }
    userSettings->endArray();

    //laScrollStretch = new QScrollBar
    QHBoxLayout *numpadLayout = new QHBoxLayout();

    npad = new Omnibox(this);
    npadMode = ChequeForm_MnK::NpadNormalReading;

    connect(npad, SIGNAL(inputChanged(QString)), this, SLOT(on_npad_textChanged(QString)));
    connect(npad, SIGNAL(inputCommited(QString)), this, SLOT(on_npad_textCommited(QString)));

    numpadLayout->addWidget(npad);
    //    numpadLayout->addStretch(1);

    setFocusProxy(npad);

    this->installEventFilter(this);


    QVBoxLayout *buttonsLayout = new QVBoxLayout();


    buttonsLayout->setContentsMargins(settings->value("globals/button_hmargin").toInt(),0,0,0);
    buttonsLayout->setSpacing(settings->value("globals/button_vmargin").toInt()*2);

    if (settings->value("devices/comportscales/is_enabled", false).toBool()){
        QPushButton *btWeight = new QPushButton("Вес",this);
        btWeight->setMaximumSize(settings->value("globals/button_width").toInt() * 2 + settings->value("globals/button_hmargin").toInt(), settings->value("globals/button_height").toInt());
        btWeight->setMinimumSize(settings->value("globals/button_width").toInt() * 2 + settings->value("globals/button_hmargin").toInt(), settings->value("globals/button_height").toInt());
        btWeight->setFocusPolicy(Qt::NoFocus);
        buttonsLayout->addWidget(btWeight);
        connect(btWeight, SIGNAL(clicked()), this, SLOT(getWeight()));
    }

    if(!settings->value("queries/cheque/dpayers_list").toString().isEmpty()){
        QPushButton *btPayers = new QPushButton("В долг",this);
        btPayers->setMaximumSize(settings->value("globals/button_width").toInt() * 2 + settings->value("globals/button_hmargin").toInt(), settings->value("globals/button_height").toInt());
        btPayers->setMinimumSize(settings->value("globals/button_width").toInt() * 2 + settings->value("globals/button_hmargin").toInt(), settings->value("globals/button_height").toInt());
        btPayers->setFocusPolicy(Qt::NoFocus);
        buttonsLayout->addWidget(btPayers);
        connect(btPayers, SIGNAL(clicked()), this, SLOT(showDPayers()));
    }


    QPushButton *btReconnect = new QPushButton("Обновить",this);
    btReconnect->setMaximumSize(settings->value("globals/button_width").toInt() * 2 + settings->value("globals/button_hmargin").toInt(), settings->value("globals/button_height").toInt());
    btReconnect->setMinimumSize(settings->value("globals/button_width").toInt() * 2 + settings->value("globals/button_hmargin").toInt(), settings->value("globals/button_height").toInt());
    btReconnect->setFocusPolicy(Qt::NoFocus);
    buttonsLayout->addWidget(btReconnect);
    connect(btReconnect, SIGNAL(clicked()), this, SLOT(reconnectDevices()));


    QPushButton *btCommit = new QPushButton("Пробить",this);
    btCommit->setMaximumSize(settings->value("globals/button_width").toInt() * 2 + settings->value("globals/button_hmargin").toInt(), settings->value("globals/button_height").toInt());
    btCommit->setMinimumSize(settings->value("globals/button_width").toInt() * 2 + settings->value("globals/button_hmargin").toInt(), settings->value("globals/button_height").toInt());
    btCommit->setFocusPolicy(Qt::NoFocus);

    buttonsLayout->addStretch(1);
    buttonsLayout->addWidget(btCommit);

    connect(btCommit, SIGNAL(clicked()), this, SLOT(on_btCommit_clicked()));

    serial = 0; // init
    reconnectDevices();


    mainLayout->addWidget(goodsTable,0,0,1,3);
    mainLayout->addLayout(goodsLeftTableFooter,1,0);
    mainLayout->addWidget(lbSumm,1,1);
    mainLayout->addWidget(summTotals,1,2);

    mainLayout->addLayout(numpadLayout, 2, 0);
    mainLayout->addWidget(lbPayed, 2, 1);
    mainLayout->addWidget(summPayed, 2, 2);
    connect(summPayed, SIGNAL(textChanged(QString)), this, SLOT(calcSummReturn(QString)));

    mainLayout->addWidget(lbReturn, 3, 1);
    mainLayout->addWidget(summReturn, 3, 2);

    //laStretch->addWidget(searchTable);
    mainLayout->addWidget(searchTable,4,0,1,3);

    goodsSelectorScroll = new QScrollArea(this);
    //     scrollArea->setBackgroundRole(QPalette::Dark);
    goodsSelectorScroll->setWidget(goodsSelector);


    mainLayout->addWidget(goodsSelectorScroll,4,0,1,3);

    mainLayout->addLayout(buttonsLayout, 0, 3, 6, 1);

    groupbuttons_are_visible = settings->value("queries/cheque/groupbuttons_are_visible").toInt();
    if(!groupbuttons_are_visible)goodsSelector->hide();

}

ChequeForm_MnK::~ChequeForm_MnK()
{
    QSettings *userSettings = Settings::getUserInstance();

    userSettings->beginWriteArray("cheque/preferences/goodsTable");
    for(int i=0;i<goodsTable->columnCount();++i){
        userSettings->setArrayIndex(i);
        userSettings->setValue("width", goodsTable->columnWidth(i));
    }
    userSettings->endArray();

    userSettings->beginWriteArray("cheque/preferences/searchTable");
    for(int i=0;i<searchModel->columnCount();++i){
        userSettings->setArrayIndex(i);
        userSettings->setValue("width", searchTable->columnWidth(i));
    }
    userSettings->endArray();
}


bool ChequeForm_MnK::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

        if(keyEvent->key()==Qt::Key_F5){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие F5 - переходим к чтению веса";

            getWeight();
            return true;
        }

        // F6 - input Qty


        if(keyEvent->key()==Qt::Key_F6){
            if(groupbuttons_are_visible){
                goodsSelector->hide();
                groupbuttons_are_visible = 0;
            }else{
                goodsSelector->show();
                groupbuttons_are_visible = 1;
            }

            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие F6 - кнопки групп "<<(groupbuttons_are_visible?"видимы":"невидимы");

            return true;
        }


        if(keyEvent->key()==Qt::Key_F7){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие F7 - чистим ввод, переходим в омнибокс";

            npad->clearText();
            npad->setModeLabel("");
            npad->setFocus(Qt::OtherFocusReason);
            npadMode = ChequeForm_MnK::NpadNormalReading;
            return true;
        }

        if(keyEvent->key()==Qt::Key_F8){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие F8 - переходим ко вводу суммы оплаты";

            summPayed->setFocus(Qt::OtherFocusReason);
            summPayed->selectAll();
            return true;
        }

        if(keyEvent->key()==Qt::Key_F9){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие F9 - переходим к инициализации устройств";

            reconnectDevices();
            return true;
        }

        if(keyEvent->key()==Qt::Key_F10){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие F10 - переходим к показу должников";

            showDPayers();
            return true;
        }

        if(keyEvent->key()==Qt::Key_F11){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие F11 - переходим к режиму чтения штрихкода";

            npad->clearText();
            npad->setModeLabel("");
            npad->setFocus(Qt::OtherFocusReason);
            npadMode = ChequeForm_MnK::NpadBarcodeReading;
            return true;
        }

        if(keyEvent->key()==Qt::Key_F12){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие F12 - переходим к подтверждению чека";

            on_btCommit_clicked();
            return true;
        }


        if(keyEvent->key()==Qt::Key_Down && searchTable->isVisible()){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие ВНИЗ - меняем выделенную строку в поиске";

            int row = searchTable->currentIndex().row();
            QModelIndex idx = searchTable->currentIndex().sibling(row+1,0);
            if(idx.isValid())
                searchTable->setCurrentIndex(idx);
            else{
                if(!searchTable->currentIndex().isValid()) {
                    QModelIndex idx = searchTable->indexAt(QPoint(0,0));
                    if(idx.isValid())
                        searchTable->setCurrentIndex(idx);
                }
            }
            searchTable->scrollTo(searchTable->currentIndex());//, QAbstractItemView::EnsureVisible);
            return true;
        }

        if(keyEvent->key()==Qt::Key_Up && searchTable->isVisible()){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Нажатие ВВЕРХ - меняем выделенную строку в поиске";

            int row = searchTable->currentIndex().row();
            QModelIndex idx = searchTable->currentIndex().sibling(row-1,0);
            if(idx.isValid())
                searchTable->setCurrentIndex(idx);

            searchTable->scrollTo(searchTable->currentIndex());//, QAbstractItemView::EnsureVisible);
            return true;
        }

        //    qDebug()<<posInFile<<keyEvent->key()<<keyEvent->modifiers();

        /*
        // Enter is currently read as Alt
        if((keyEvent->key()==Qt::Key_Enter || keyEvent->key()==Qt::Key_Alt) && searchTable->isVisible()){
            on_searchTable_elementSelected(searchTable->currentIndex());
            qDebug()<<searchTable->currentIndex();
            return true;
        }
*/

    }

    return QWidget::eventFilter(obj, event);
}


void ChequeForm_MnK::addGoods(int GOODS_ID, double kol_add)
{

    if(loglevel > 2)
        qDebug()<<(loglevel>1?posInFile:"")<<"Перед добавлением - проверим последний товар - не пустой весовой ли";

    QSettings *settings = Settings::getInstance();

    if (goodsTable->rowCount() > 0){
        QSqlQuery query;
        query.prepare(settings->value("queries/cheque/check_is_wgh_goods").toString());
        QTableWidgetItem *iid = goodsTable->item(goodsTable->rowCount()-1,0);
        query.bindValue(":val",iid->text().toInt());

        if(!query.exec()){
            if(loglevel > 0)
                qDebug()<<(loglevel>1?posInFile:"")<<"Ошибка проверки на необходимость веса"
                       <<query.lastError().text()<<endl
                      <<query.lastQuery()<<endl
                     <<query.boundValues();
            return;
        }

        query.next();
        int test = query.value(0).toInt();

        if(test==1)
            if(loglevel > 2){
                qDebug()<<(loglevel>1?posInFile:"")<<"Последний товар весовой - проверим вес";
                if (goodsTable->item(goodsTable->rowCount()-1,4)->text().toDouble()==0){
                    qDebug()<<(loglevel>1?posInFile:"")<<"Последний товар весовой и нулевой - ругаемся!!!";

                    QMessageBox message;
                    message.setText("Ошибка: предыдущий весовой товар не взвешен");
                    message.exec();
                    return;
                }
            }
    }

    if(loglevel > 2)
        qDebug()<<(loglevel>1?posInFile:"")<<"Добавление товара код: "<<GOODS_ID<<" кол-во: "<<kol_add;

    if(kol_add==1){
        QSqlQuery query;
        QString qsw  = Settings::getInstance()->value("queries/cheque/check_is_wgh_goods").toString();

        if(!qsw.isEmpty()){
            query.prepare(qsw);
            query.bindValue(":val",GOODS_ID);

            if(!query.exec()){
                if(loglevel > 0)
                    qDebug()<<(loglevel>1?posInFile:"")<<"Ошибка проверки на весовой товар: "
                           <<query.lastError().text()<<endl
                          <<query.lastQuery()<<endl
                         <<query.boundValues();
                return;
            }

            if (query.next())
                if(query.value(0).toInt()==1){
                    kol_add = 0;
                    if(loglevel > 2)
                        qDebug()<<(loglevel>1?posInFile:"")<<"Товар весовой - сбрасываем количество в 0: ";

                }
        }
    }



    bool is_new = true;

    if(loglevel > 2)
        qDebug()<<(loglevel>1?posInFile:"")<<"Проверяем - есть ли такой товар уже в чеке ";

    for (int i = 0; i < goodsTable->rowCount() && is_new && kol_add; ++i)
    {
        if(goodsTable->item(i, 0)->data(Qt::DisplayRole)==GOODS_ID)
        {
            is_new    = false;
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Товар есть - в строке "<<i<<"  в количестве "<<goodsTable->item(i, 4)->data(Qt::DisplayRole).toDouble()<<" добавляем : "<<kol_add;

            goodsTable->item(i,4)->setData(Qt::DisplayRole, QString::number(kol_add + goodsTable->item(i, 4)->data(Qt::DisplayRole).toDouble()));
            goodsTable->selectRow(i);

            lastAction->setText("+"+QString::number(kol_add)+" х "+(goodsTable->item(i,1)->data(Qt::DisplayRole).toString())+" "+(goodsTable->item(i,2)->data(Qt::DisplayRole).toString()));
        }
    }


    if(is_new)
    {

        QSqlQuery que;
        que.prepare(Settings::getInstance()->value("queries/cheque/search_goods_by_id").toString());
        que.bindValue(":val",GOODS_ID);
        if(!que.exec()){
            if(loglevel > 0)
                qDebug()<<(loglevel>1?posInFile:"")<<"Ошибка поиска товара по коду "
                       <<que.lastError().text()<<endl
                      <<que.lastQuery()<<endl
                     <<que.boundValues();
            return;
        }

        if(!que.next()){
            if(loglevel > 0)
                qDebug()<<(loglevel>1?posInFile:"")<<"Невозможно найти такой товар (бред, да?) выходим";
            return;
        };

        int nrow = goodsTable->rowCount();

        if(loglevel > 2)
            qDebug()<<(loglevel>1?posInFile:"")<<"Товара нет - добавляем новую строку "<<nrow;

        goodsTable->insertRow(nrow);
        goodsTable->setItem(nrow,0,new QTableWidgetItem(QString::number(GOODS_ID)));
        goodsTable->setItem(nrow,1,new QTableWidgetItem(que.value(0).toString()));
        goodsTable->setItem(nrow,2,new QTableWidgetItem(que.value(1).toString()));
        // обратный порядок чтобы при вставке кол-ва уже был итем суммы и чтобы она автоматом посчиталась
        goodsTable->setItem(nrow,7,new QTableWidgetItem("0"));
        goodsTable->setItem(nrow,6,new QTableWidgetItem(QString::number(que.value(2).toDouble(), 'f', 2)));
        goodsTable->setItem(nrow,4,new QTableWidgetItem(QString::number(kol_add)));

        goodsTable->setItem(nrow,5,new QTableWidgetItem("+"));
        goodsTable->setItem(nrow,3,new QTableWidgetItem("-"));
        goodsTable->selectRow(nrow);

        lastAction->setText(QString::number(kol_add)+" х "+(que.value(0).toString())+" "+(que.value(1).toString()));
    }

    addSumm(0);
}


void ChequeForm_MnK::addSumm(double summ_add){
    if(loglevel > 2)
        qDebug()<<(loglevel>1?posInFile:"")<<"Перерисовываем сумму к "<<summTotals->text().toDouble()<<" добавляем "<<summ_add;

    double sum = summTotals->text().toDouble()+summ_add;
    summTotals->setText(QString::number(sum, 'f', 2));
    formatSummPayed();
}

void ChequeForm_MnK::on_goodsTable_currentCellChanged(int,int,int,int){
    if (npadMode==ChequeForm_MnK::NpadQtyReading || npadMode==ChequeForm_MnK::NpadPriceReading){
        if(loglevel > 2)
            qDebug()<<(loglevel>1?posInFile:"")<<"Закончено редактирование "<<(npadMode==ChequeForm_MnK::NpadQtyReading?"количества":"")<<(npadMode==ChequeForm_MnK::NpadPriceReading?"цены":"");

        npadMode=ChequeForm_MnK::NpadNormalReading;
        npad->setModeLabel("");
        npad->clearText();
        npad->setFocus(Qt::OtherFocusReason);
    }
}

void ChequeForm_MnK::on_goodsTable_cellChanged(int row, int column)
{

    if(column==4 || column==6)
    {
        if(loglevel > 2)
            qDebug()<<(loglevel>1?posInFile:"")<<"Изменилась ячейка, строка "<<row<<"колонка"<<(column==4?" количество":"")<<(column==6?" цена":"");

        QTableWidgetItem *isumm  = goodsTable->item(row,7);

        QTableWidgetItem *iprice    = goodsTable->item(row,6);

        if(column==6){
            QString s1 = iprice->data(Qt::DisplayRole).toString();
            s1.replace(QString(","),QString("."));
            iprice->setData(Qt::DisplayRole,s1);
        }

        QTableWidgetItem *ikol       = goodsTable->item(row,4);
        if(column==4){
            QString s1 = ikol->data(Qt::DisplayRole).toString();
            s1.replace(QString(","),QString("."));
            ikol->setData(Qt::DisplayRole,s1);
        }

        if(!ikol || !iprice || !isumm)
            return;

        double before = Service::round(isumm->data(Qt::DisplayRole).toDouble(),2);
        double after   = Service::round(ikol->data(Qt::DisplayRole).toDouble() * iprice->data(Qt::DisplayRole).toDouble(),2);

        addSumm(after-before);

        if(after!=before)
            isumm->setText(QString::number(after, 'f', 2));

        lastAction->setText(" * "+(goodsTable->item(row,1)->data(Qt::DisplayRole).toString())+" "+(goodsTable->item(row,2)->data(Qt::DisplayRole).toString()));

    }

}

void ChequeForm_MnK::on_goodsTable_cellClicked(int row, int column)
{
    if(column==3 || column==5)
    {
        if(loglevel > 2)
            qDebug()<<(loglevel>1?posInFile:"")<<"Клик по ячейке, строка "<<row<<"колонка"<<(column==3?" минус":"")<<(column==5?" плюс":"");

        QTableWidgetItem *ikol       = goodsTable->item(row,4);
        if(!ikol)
            return;

        int delta = column==3?-1:1;

        if(ikol->data(Qt::DisplayRole).toDouble() + delta<=0){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"В количестве получается меньше 0 - убираем строку ";

            // kill
            QTableWidgetItem *isumm       = goodsTable->item(row,7);
            addSumm(-isumm->data(Qt::DisplayRole).toDouble());
            lastAction->setText(" - "+(goodsTable->item(row,1)->data(Qt::DisplayRole).toString())+" "+(goodsTable->item(row,2)->data(Qt::DisplayRole).toString()));
            goodsTable->removeRow(row);
        }else
            // correct. here will be normal
            ikol->setText(QString::number(ikol->data(Qt::DisplayRole).toDouble() + delta));

    }
}


void ChequeForm_MnK::on_npad_textChanged(const QString& text)
{
    if(loglevel > 2)
        qDebug()<<(loglevel>1?posInFile:"")<<"Поиск по омнибоксу строки:"<<text;

    if(text.length()>0){
        goodsSelectorScroll->hide();
        searchTable->show();
    }else{
        goodsSelectorScroll->show();
        searchTable->hide();
    }


    if(npadMode==ChequeForm_MnK::NpadNormalReading){
        if(firstSearch){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Первый раз читаем список товаров - надо выбрать все ";

            while(searchModel->canFetchMore())
                searchModel->fetchMore();
            //            searchProxy->setFilter("-","1");
            firstSearch = false;
        }

        bool ok = false;
        text.toLongLong(&ok);

        if(ok)
            if(text.length()<6)
                searchProxy->setFilter(text,"=2");
            else
                searchProxy->setFilter(text,"1,=2,3,4");
        else
            searchProxy->setFilter(text,"3,4");

    }


}

void ChequeForm_MnK::on_npad_textCommited(const QString& text)
{
    QString txt = text;
    if(npadMode==ChequeForm_MnK::NpadNormalReading && (text.startsWith("i",Qt::CaseInsensitive) || text.startsWith("ш",Qt::CaseInsensitive))){
        bool ok = false;
        text.mid(1).toLongLong(&ok);
        if(ok){
            npadMode=ChequeForm_MnK::NpadBarcodeReading;
            txt = text.mid(1);
        }
    }

    if(npadMode==ChequeForm_MnK::NpadNormalReading){
        if(searchTable->isVisible()){
            on_searchTable_elementSelected(searchTable->currentIndex());
        }else{
            addGoods(searchProxy->getValue(0,0).toInt(),1.0);
        }
    }

    // 4823003205588
    if(npadMode==ChequeForm_MnK::NpadBarcodeReading){

        QSqlQuery que;
        que.prepare(Settings::getInstance()->value("queries/cheque/search_by_barcode").toString());
        que.bindValue(":val", txt.toLongLong());

        if(!que.exec()){
            if(loglevel > 0)
                qDebug()<<(loglevel>1?posInFile:"")<<"Ошибка поиска штрихкода"
                       <<que.lastError().text()<<endl
                      <<que.lastQuery()<<endl
                     <<que.boundValues();
            lastAction->setText("Ошибка поиска штрихкода "+txt);
        }else
            if(que.next()){
                addGoods(que.value(0).toInt(),1.0);
            }else{
                que.prepare(Settings::getInstance()->value("queries/cheque/search_by_articul").toString());
                que.bindValue(":val", txt.left(txt.length()-1));

                if(!que.exec()){
                    if(loglevel > 0)
                        qDebug()<<(loglevel>1?posInFile:"")<<"Ошибка поиска по артикулу"
                               <<que.lastError().text()<<endl
                              <<que.lastQuery()<<endl
                             <<que.boundValues();
                    lastAction->setText("Ошибка поиска штрихкода "+txt);
                }else
                    if(que.next()){
                        addGoods(que.value(0).toInt(),1.0);
                    }else{
                        lastAction->setText("Ошибка поиска штрихкода "+txt);
                        if(loglevel > 2)
                            qDebug()<<(loglevel>1?posInFile:"")<<"Текст "<<txt<<"не найден а базе";

                    }
            }
        npad->clearText();
        npad->setFocus(Qt::OtherFocusReason);
    }


    if(npadMode==ChequeForm_MnK::NpadQtyReading){
        QTableWidgetItem *ikol       = goodsTable->item(goodsTable->currentRow(),4);
        ikol->setText(text);
    }

    if(npadMode==ChequeForm_MnK::NpadPriceReading){
        QTableWidgetItem *iprc       = goodsTable->item(goodsTable->currentRow(),6);
        iprc->setText(text);
    }


    npadMode = ChequeForm_MnK::NpadNormalReading;
    npad->setModeLabel("");
}


void ChequeForm_MnK::on_searchTable_elementSelected(QModelIndex mi)
{
    //    qDebug()<<posInFile<<searchProxy->getValue(mi.row(),0).toInt();
    addGoods(searchProxy->getValue(mi.row(),0).toInt(),1.0);
    npad->clearText();
    npad->setFocus(Qt::OtherFocusReason);
    npadMode = ChequeForm_MnK::NpadNormalReading;
}

void ChequeForm_MnK::on_barcode_readyRead()
{
    QByteArray barcode = serial->readAll();
    while (serial->waitForReadyRead(10))
        barcode += serial->readAll();
    barcode = barcode.simplified();

    QSqlQuery que;
    que.prepare(Settings::getInstance()->value("queries/globals/search_by_barcode").toString());
    que.bindValue(":val", barcode);

    if(que.next()){
        addGoods(que.value(0).toInt(),1.0);
    }else{
        lastAction->setText("Ошибка поиска штрихкода "+barcode);
        if(loglevel > 0)
            qDebug()<<(loglevel>1?posInFile:"")<<"Ошибка поиска штрихкода"<<barcode;
        npad->clearText();
        npad->setFocus(Qt::OtherFocusReason);
    }
}


void ChequeForm_MnK::on_groupSelected(const QString &params){
    QDialog *dlg = new QDialog();

    QSettings *settings = Settings::getInstance();

    QSqlQueryModel *searchModel = new QSqlQueryModel(dlg);
    QString squery = settings->value("queries/cheque/groupslist_with_params_preffics").toString();
    if (!params.isEmpty())
        squery += " "+settings->value("queries/cheque/groupslist_with_params_where").toString() +" "+params;
    squery += QString(" ")+settings->value("queries/cheque/groupslist_with_params_suffics").toString();

    QSqlQuery query;
    query.prepare(squery);

    if(!query.exec()){
        if(loglevel > 0)
            qDebug()<<(loglevel>1?posInFile:"")<<"Ошибка показа товаров в группе "<<params
                   <<query.lastError().text()<<endl
                  <<query.lastQuery()<<endl
                 <<query.boundValues();

        return;
    }

    searchModel->setQuery(query);

    QTableView *searchTable = new QTableView(dlg);
    searchTable->setModel(searchModel);
    searchTable->verticalHeader()->setVisible(false);
    searchTable->verticalHeader()->setDefaultSectionSize(settings->value("globals/button_height").toInt());

    searchTable->hideColumn(0);
    searchModel->setHeaderData(1, Qt::Horizontal, "Арт.");
    searchModel->setHeaderData(2, Qt::Horizontal, "Название");
    searchModel->setHeaderData(3, Qt::Horizontal, "Производитель");
    searchModel->setHeaderData(4, Qt::Horizontal, "Цена");
    searchModel->setHeaderData(5, Qt::Horizontal, "Остаток");

    searchTable->setSelectionMode(QAbstractItemView::SingleSelection);
    searchTable->setSelectionBehavior(QAbstractItemView::SelectRows);


    SmartDelegate *dgsum = new SmartDelegate(this);
    dgsum->setPrecision(2);
    dgsum->setReadOnly();
    searchTable->setItemDelegateForColumn(4, dgsum);

    SmartDelegate *dgkol = new SmartDelegate(this);
    dgsum->setReadOnly();
    searchTable->setItemDelegateForColumn(5, dgkol);


    QHBoxLayout *la = new  QHBoxLayout(dlg);
    la->addWidget(searchTable);

    connect(searchTable, SIGNAL(clicked(QModelIndex)), dlg, SLOT(accept()));

    QSettings *userSettings = Settings::getUserInstance();

    int size= userSettings->beginReadArray("cheque/preferences/selectordialog/table");
    for(int i=0;i<size;++i){
        userSettings->setArrayIndex(i);
        searchTable->setColumnWidth(i, userSettings->value("width",50).toInt());
    }
    userSettings->endArray();

    QRect geometry = QApplication::desktop()->screenGeometry();
    dlg->setMinimumSize(geometry.width(), geometry.height());//settings->value("cheque/preferences/selectordialog/width",800).toInt(), settings->value("cheque/preferences/selectordialog/height",600).toInt());


    if (dlg->exec()){
        QModelIndex mi = searchTable->currentIndex();
        mi = mi.sibling(mi.row(), 0);
        addGoods(searchModel->data(mi).toInt(),1.0);
    }

    userSettings->setValue("cheque/preferences/selectordialog/width", dlg->size().width());
    userSettings->setValue("cheque/preferences/selectordialog/height", dlg->size().height());

    userSettings->beginWriteArray("cheque/preferences/selectordialog/table");
    for(int i=0;i<searchModel->columnCount();++i){
        userSettings->setArrayIndex(i);
        userSettings->setValue("width", searchTable->columnWidth(i));
    }
    userSettings->endArray();

    delete dlg;
}

void ChequeForm_MnK::on_btCommit_clicked()
{
    QSettings *settings = Settings::getInstance();


    if (goodsTable->rowCount() == 0){
        if(loglevel > 0)
            qDebug()<<(loglevel>1?posInFile:"")<<"Попытка пробить пустой чек";

        QMessageBox message;
        message.setText("Ошибка: чек пустой");
        message.exec();

        return;
    }




    if (goodsTable->rowCount() > 0){
        QSqlQuery query;
        query.prepare(settings->value("queries/cheque/check_is_wgh_goods").toString());
        QTableWidgetItem *iid = goodsTable->item(goodsTable->rowCount()-1,0);
        query.bindValue(":val",iid->text().toInt());

        if(!query.exec()){
            if(loglevel > 0)
                qDebug()<<(loglevel>1?posInFile:"")<<"Ошибка проверки на необходимость веса"
                       <<query.lastError().text()<<endl
                      <<query.lastQuery()<<endl
                     <<query.boundValues();
            return;
        }

        query.next();
        int test = query.value(0).toInt();

        if(test==1)
            if(loglevel > 2){
                qDebug()<<(loglevel>1?posInFile:"")<<"Последний товар весовой - проверим вес";
                if (goodsTable->item(goodsTable->rowCount()-1,4)->text().toDouble()==0){
                    qDebug()<<(loglevel>1?posInFile:"")<<"Последний товар весовой и нулевой - ругаемся!!!";

                    QMessageBox message;
                    message.setText("Ошибка: предыдущий весовой товар не взвешен");
                    message.exec();
                    return;
                }
            }
    }


    if(loglevel > 2)
        qDebug()<<(loglevel>1?posInFile:"")<<"Сохранение чека";

    QSqlDatabase db = QSqlDatabase::database();
    db.transaction();

    QSqlQuery query(db);

    //    QSettings *settings = Settings::getInstance();

    if(!query.exec(settings->value("queries/cheque/get_new_document_id").toString())){
        db.rollback();
        qCritical()<<(loglevel>1?posInFile:"")<<"Ошибка получения id документа"<<endl<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();

        QMessageBox message;
        message.setText("Ошибка сохранения документа\nТекст: \n"+query.lastError().text()+"\nЗапрос:\n"+query.lastQuery());
        message.exec();

        return;
    }

    query.next();
    int doc_id = query.value(0).toInt();


    //if(1==0){
    if(params.contains("cheque for return")){
        query.prepare(settings->value("queries/cheque/save_cheque_for_return").toString());
    }else{
        query.prepare(settings->value("queries/cheque/save_cheque").toString());
    }

    query.bindValue(":id", doc_id);
    query.bindValue(":ndoc", QString::number(doc_id));
    query.bindValue(":data", QDate::currentDate());
    query.bindValue(":store", Settings::getDefinition("ТЕКУЩАЯ_БАЗА").toInt());
    query.bindValue(":user", Settings::getVariables()->value("user_id").toInt());

    QString s1 = summPayed->text();
    s1.replace(QString(","),QString("."));
    double res = s1.toDouble();
    query.bindValue(":summ", res);

    if(loglevel > 2)
        qDebug()<<(loglevel>1?posInFile:"")<<"Запрос на добавление документа"
               <<"Запрос: "<<query.lastQuery()<<endl
              <<"Значения: "<<query.boundValues();

    if(!query.exec()){
        db.rollback();
        qCritical()<<(loglevel>1?posInFile:"")<<"Ошибка добавления нового документа"<<endl<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();

        QMessageBox message;
        message.setText("Ошибка сохранения документа\nТекст: \n"+query.lastError().text()+"\nЗапрос:\n"+query.lastQuery());
        message.exec();
        return;
    }


    for (int i = 0; i < goodsTable->rowCount(); ++i) {
        if(!query.exec(settings->value("queries/cheque/get_new_document_pos_id").toString())){
            db.rollback();

            qCritical()<<(loglevel>1?posInFile:"")<<"Ошибка получения id строки документа"<<endl<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();

            QMessageBox message;
            message.setText("Ошибка сохранения документа\nТекст: \n"+query.lastError().text()+"\nЗапрос:\n"+query.lastQuery());
            message.exec();

            return;
        }

        query.next();
        int dgoods_id = query.value(0).toInt();


        query.prepare(settings->value("queries/cheque/save_document_pos").toString());

        query.bindValue(":id",dgoods_id);
        query.bindValue(":document_id",doc_id);

        query.bindValue(":goods_id",goodsTable->item(i,0)->data(Qt::DisplayRole).toInt());
        query.bindValue(":kol",goodsTable->item(i,4)->data(Qt::DisplayRole).toDouble());
        query.bindValue(":price",goodsTable->item(i,6)->data(Qt::DisplayRole).toDouble());
        query.bindValue(":summ",goodsTable->item(i,7)->data(Qt::DisplayRole).toDouble());


        if(loglevel > 2)
            qDebug()<<(loglevel>1?posInFile:"")<<"Запрос на добавление строки документа"<<endl
                   <<"Запрос: "<<query.lastQuery()<<endl
                  <<"Значения: "<<query.boundValues();

        if(!query.exec()){
            db.rollback();
            qCritical()<<(loglevel>1?posInFile:"")<<"Ошибка добавления строки документа"<<endl<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();

            QMessageBox message;
            message.setText("Ошибка сохранения документа\nТекст: \n"+query.lastError().text()+"\nЗапрос:\n"+query.lastQuery());
            message.exec();

            return;
        }
    }

    if(!db.commit()){
        qCritical()<<(loglevel>1?posInFile:"")<<"Ошибка подтверждения документа";

        QMessageBox message;
        message.setText("Ошибка сохранения документа\nТекст: \n"+db.lastError().text());
        message.exec();

        return;
    }

    if(settings->value("devices/printer/is_enabled").toBool()){
        if(loglevel > 2)
            qDebug()<<(loglevel>1?posInFile:"")<<"Печатаем чек";

        Service::printCheque(doc_id);
    }


    if(loglevel > 2)
        qDebug()<<(loglevel>1?posInFile:"")<<"Чистим документ";

    npad->clearText();
    npad->setFocus(Qt::OtherFocusReason);

    for(int i=goodsTable->rowCount(); i>0;--i)
        goodsTable->removeRow(i-1);
    summTotals->setText(QString::number(0, 'f', 2));
    summPayed->setText(QString::number(0, 'f', 2));
    formatSummPayed();

    searchModel->setQuery(settings->value("queries/cheque/goodslist").toString());
    firstSearch = true;

    lastAction->setText("Чек №"+QString::number(doc_id)+" сохранен");

    emit chequeCommited();
}

void ChequeForm_MnK::showDPayers(){
    QDialog *dlg = new QDialog();

    QSettings *settings = Settings::getInstance();

    QSqlQueryModel *searchModel = new QSqlQueryModel(dlg);

    QSqlQuery query;
    query.prepare(settings->value("queries/cheque/dpayers_list").toString());

    if(!query.exec()){
        qCritical()<<(loglevel>1?posInFile:"")<<"Ошибка добавления строки документа"<<endl<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues();

        QMessageBox message;
        message.setText("Ошибка получения списка должников\nТекст: \n"+query.lastError().text()+"\nЗапрос:\n"+query.lastQuery());
        message.exec();
        return;
    }

    searchModel->setQuery(query);

    QTableView *searchTable = new QTableView(dlg);
    searchTable->setModel(searchModel);
    searchTable->verticalHeader()->setVisible(false);
    searchTable->verticalHeader()->setDefaultSectionSize(settings->value("globals/button_height").toInt());

    searchTable->hideColumn(0);
    searchModel->setHeaderData(1, Qt::Horizontal, "ФИО");
    searchModel->setHeaderData(2, Qt::Horizontal, "Ограничение");
    searchModel->setHeaderData(3, Qt::Horizontal, "Осталось");

    SmartDelegate *dgsum = new SmartDelegate(this);
    dgsum->setPrecision(2);
    dgsum->setReadOnly();
    searchTable->setItemDelegateForColumn(2, dgsum);
    searchTable->setItemDelegateForColumn(3, dgsum);

    QHBoxLayout *la = new  QHBoxLayout(dlg);
    la->addWidget(searchTable);

    connect(searchTable, SIGNAL(clicked(QModelIndex)), dlg, SLOT(accept()));

    QSettings *userSettings = Settings::getUserInstance();

    int size= userSettings->beginReadArray("cheque/preferences/dpayers/table");
    for(int i=0;i<size;++i){
        userSettings->setArrayIndex(i);
        searchTable->setColumnWidth(i, userSettings->value("width",50).toInt());
    }
    userSettings->endArray();

    QRect geometry = QApplication::desktop()->screenGeometry();
    dlg->setMinimumSize(geometry.width(), geometry.height());

    if (dlg->exec()){
        QModelIndex mi = searchTable->currentIndex();
        mi = mi.sibling(mi.row(), 0);
        addGoods(searchModel->data(mi).toInt(),1.0);
    }

    userSettings->setValue("cheque/preferences/dpayers/width", dlg->size().width());
    userSettings->setValue("cheque/preferences/dpayers/height", dlg->size().height());

    userSettings->beginWriteArray("cheque/preferences/dpayers/table");
    for(int i=0;i<searchModel->columnCount();++i){
        userSettings->setArrayIndex(i);
        userSettings->setValue("width", searchTable->columnWidth(i));
    }
    userSettings->endArray();

    delete dlg;
}

void ChequeForm_MnK::getWeight(){
    QSettings *settings = Settings::getInstance();

    if(!settings->value("devices/comportscales/is_enabled").toBool())
        return;

    goodsTable->clearSelection();

    if (goodsTable->rowCount() > 0){
        QSqlQuery query;
        query.prepare(settings->value("queries/cheque/check_is_wgh_goods").toString());
        QTableWidgetItem *iid = goodsTable->item(goodsTable->rowCount()-1,0);
        query.bindValue(":val",iid->text().toInt());

        if(!query.exec()){
            if(loglevel > 0)
                qDebug()<<(loglevel>1?posInFile:"")<<"Ошибка проверки на необходимость веса"
                       <<query.lastError().text()<<endl
                      <<query.lastQuery()<<endl
                     <<query.boundValues();
            return;
        }

        query.next();
        int test = query.value(0).toInt();

        if(test==0){

            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Попытка взвешивания не-весового товара";

            QMessageBox message;
            message.setText("Вы уверены, что хотите взесить НЕ-весовой товар?");
            message.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
            int result = message.exec();
            if(result!=QMessageBox::Yes)
                return;

            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Подтвердили что взвешиваем не-весовой товар";
        }
    }else{
        if(loglevel > 2)
            qDebug()<<(loglevel>1?posInFile:"")<<"Попытка взвешивания без товара";

        QMessageBox message;
        message.setText("Ошибка: Нет товара для взвешивания?");
        message.exec();
        return;
    }

    QSerialPort serial;
    QString dev = settings->value("devices/comportscales/device").toString();

    serial.setPortName(dev);
    if (serial.open(QIODevice::ReadWrite)){
        serial.setStopBits((QSerialPort::StopBits)settings->value("devices/comportscales/stopbits").toInt()); // 1-1 stop bit, 3-1.5 stop bits, 2-2 stop bits
        serial.setDataBits((QSerialPort::DataBits)settings->value("devices/comportscales/databits").toInt()); // 5-8
        serial.setParity((QSerialPort::Parity)settings->value("devices/comportscales/parity").toInt()); // 0-No parity, 2-Even parity, 3-Odd parity,4-Space parity, 5-Mark parity.
        serial.setBaudRate((QSerialPort::BaudRate)settings->value("devices/comportscales/baudrate").toInt());  // 1200,  2400, 4800, 9600, 19200...
    }

    //  double wgh = 0;

    // а теперь, собственно, читаем вес
    QByteArray writeData;
    writeData.resize(11);
    for(int i=0;i<10;++i)
        writeData[i] = 0x00;
    writeData[10]= 0x03;

    double wgh = 0;
    for(int i_reading=0;i_reading<2; i_reading++){

        // 1
        serial.write(writeData);
        if (!serial.waitForReadyRead(100)){

            if(loglevel > 0)
                qDebug()<<(loglevel>1?posInFile:"")<<"Таймаут ожидания ответа №1 от весов";

            QMessageBox message;
            //message.setBackgroundRole(QPalette::WindowText);
            message.setText("Ошибка: не удалось считать вес");
            message.exec();

            serial.close();
            return;
        }
        QThread::sleep(1);

        QByteArray requestData1 = serial.readAll();
        while (serial.waitForReadyRead(10))
            requestData1 += serial.readAll();


        int wgh_1=0;
        for(int i=5;i>=0;--i)
            wgh_1 = wgh_1 * 10 + requestData1[i];

        if(loglevel > 2)
            qDebug()<<(loglevel>1?posInFile:"")<<"Прочитано "<<requestData1<<". Преобразовали в "<<wgh_1;

        // 2
        serial.write(writeData);

        if (!serial.waitForReadyRead(100)){
            if(loglevel > 0)
                qDebug()<<(loglevel>1?posInFile:"")<<"Таймаут ожидания ответа №2 от весов";

            QMessageBox message;
            message.setText("Ошибка: не удалось считать вес");
            message.exec();

            serial.close();
            return;
        }

        QThread::sleep(1);
        QByteArray requestData2 = serial.readAll();
        while (serial.waitForReadyRead(10))
            requestData2 += serial.readAll();

        int wgh_2=0;
        for(int i=5;i>=0;--i)
            wgh_2 = wgh_2 * 10 + requestData2[i];


        if(loglevel > 2)
            qDebug()<<(loglevel>1?posInFile:"")<<"Прочитано "<<requestData2<<". Преобразовали в "<<wgh_2;

        if(wgh_1==wgh_2){
            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Вес  совпал, сохраняем, выходим";

            wgh = (double)wgh_1 / 1000;
            break;
        }else{

            QMessageBox message;
            message.setText("Ошибка: не удалось считать вес");
            message.exec();
            return;

            if(loglevel > 2)
                qDebug()<<(loglevel>1?posInFile:"")<<"Вес  не совпал";
        }
    }

    serial.close();
    //return wgh;

    QTableWidgetItem *ikol2       = goodsTable->item(goodsTable->rowCount()-1,4);
    ikol2->setText(QString::number(wgh));

    goodsTable->selectRow(goodsTable->rowCount()-1);

}


void ChequeForm_MnK::formatSummPayed(){
    bool ok = false;
    QString s1 = summPayed->text();
    s1.replace(QString(","),QString("."));
    double res = s1.toDouble(&ok);

    summPayed->setText(QString::number(res, 'f', 2));

    calcSummReturn(summPayed->text());

    npad->setFocus(Qt::OtherFocusReason);
}

void ChequeForm_MnK::calcSummReturn(const QString &str){
    bool ok = false;
    QString s1 = str;
    s1.replace(QString(","),QString("."));
    double res = s1.toDouble(&ok);

    res = res - summTotals->text().toDouble();

    if(res >= 0)
        summReturn->setText(QString::number(res, 'f', 2));
    else
        summReturn->setText("--------");
}



void ChequeForm_MnK::reconnectDevices(){
    QSettings *settings = Settings::getInstance();
    if(loglevel > 2)
        qDebug()<<(loglevel>1?posInFile:"")<<"Пересоединение с устройствами";

    searchModel->setQuery(settings->value("queries/cheque/goodslist").toString());
    firstSearch = true;


    if (settings->value("devices/comportscanner/is_enabled").toBool()==true){
        QString dev = settings->value("devices/comportscanner/device").toString();
        if (!serial)
            serial = new QSerialPort(this);
        else
            serial->close();

        serial->setPortName(dev);
        if (serial->open(QIODevice::ReadOnly)){
            serial->setStopBits((QSerialPort::StopBits)settings->value("devices/comportscanner/stopbits").toInt()); // 1-1 stop bit, 3-1.5 stop bits, 2-2 stop bits
            serial->setDataBits((QSerialPort::DataBits)settings->value("devices/comportscanner/databits").toInt()); // 5-8
            serial->setParity((QSerialPort::Parity)settings->value("devices/comportscanner/parity").toInt()); // 0-No parity, 2-Even parity, 3-Odd parity,4-Space parity, 5-Mark parity.
            serial->setBaudRate((QSerialPort::BaudRate)settings->value("devices/comportscanner/baudrate").toInt());  // 1200,  2400, 4800, 9600, 19200...

            connect(serial, SIGNAL(readyRead()), this, SLOT(on_barcode_readyRead()));
        }
    }


}
